package com.summer.lock;

import java.util.concurrent.locks.Lock;
//import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockTest {

	public static void main(String[] args) {
		
		Thread thread1 = new Thread(new Runnable() {
			@Override
			public void run() {
				for(int index=0;index<10;index++){
					LockDemo.setData(LockDemo.data+1);
					System.out.println(Thread.currentThread().getName()+":"+LockDemo.getData());
				}
			}
		});
		Thread thread2 = new Thread(new Runnable() {
			@Override
			public void run() {
				for(int index=0;index<10;index++){
					System.out.println(Thread.currentThread().getName()+":"+LockDemo.getData());
					LockDemo.setData(LockDemo.data+1);
					
				}
			}
		});
		
		
		
		thread1.start();
		thread2.start();
//		thread.start();
	}
	
	public static class LockDemo{
		static int data=0;
//		private static Lock lock = new ReentrantLock();

//		lock.newCondition();
		
		static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
		static Lock r = rwl.readLock();
		static Lock w = rwl.writeLock();
		
		public static void setData(int _data){
//			lock.lock();
			w.lock();
			try{
			data=_data;
			}finally{
//			lock.unlock();
				w.unlock();
			}
			
		}
		
		public static int getData(){
//			lock.lock();
			r.lock();
			try{
			return data;
			}finally{
//				lock.unlock();
				r.unlock();
			}
		}
		
	}
}
